package advance.app.controller;

import advance.app.pojo.AppFileInfo;
import advance.app.pojo.AppSopFileInfo;
import advance.app.pojo.DepFileInfo;
import advance.app.pojo.SopFileInfo;
import advance.app.service.impl.AppFileInfoServiceImpl;
import advance.app.service.impl.AppSopFileInfoServiceImpl;
import advance.app.service.impl.DepFileInfoServiceImpl;
import advance.app.service.impl.SopFileInfoServiceImpl;
import advance.app.utils.FileUpload;
import advance.app.utils.ZipUtil;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@CrossOrigin
@RequestMapping("/rpt")
public class RptController {

    private static final Logger logger = LoggerFactory.getLogger(RptController.class);

    @Autowired
    private AppFileInfoServiceImpl appFileInfoService;

    @Autowired
    private SopFileInfoServiceImpl sopFileInfoService;

    @Autowired
    private DepFileInfoServiceImpl depFileInfoService;

    @Autowired
    private AppSopFileInfoServiceImpl appSopFileInfoService;

    @RequestMapping("/")
    public String home(){

        return "home";
    }

    @RequestMapping("/{area}/{type}")
    public String getFileType(Model model, @PathVariable("area") String area,
                              @PathVariable("type") String type){
        System.out.println("getFileType:"+type.toLowerCase());
        model.addAttribute("area", area);
        model.addAttribute("file_type", type.toLowerCase());
        if(type.equals("pkg")){
            return "admins/downPkgPage";
        }else{
            return "admins/downPage";
        }

    }

    /**
     * 获取APP 上传的程序压缩包，不显示WISE,显示WISE_PKG
     * @param area  8/12
     * @param version version
     * @param page
     * @param limit
     * @return
     */
    @ResponseBody
    @RequestMapping("/showAppPkgData/{area}")
    public Map<String,Object> indexShowData(
            @PathVariable("area") String area,
            @RequestParam(required=false,defaultValue="1") int page,
            @RequestParam(required=false,defaultValue="15") int limit
    ){
        int count=1;
        //从第几条数据开始
        int firstIndex = (page - 1) * limit;
        //到第几条数据结束
        int lastIndex = page * limit;
        Map<String,Object> map=new HashMap<String,Object>();

        //datas = appSopFileInfoService.getSopFileInfoByType(area, type.toUpperCase());
        List<AppFileInfo> appInfo = appFileInfoService.getNewByArea(area,"WISE");
        count = appInfo.size();
        if (lastIndex > count){
            lastIndex = count;
        }
        map.put("data",appInfo.subList(firstIndex, lastIndex));//直接在list中截取

        map.put("code",0);
        map.put("msg","success");
        map.put("count",count);

        System.out.println(map.toString());
        return map;
    }

    @ResponseBody
    @RequestMapping("/showSopData/{area}/{type}/{version}")
    public Map<String,Object> indexShowSopData(
            @PathVariable("area") String area,
            @PathVariable("type") String type,
            @PathVariable("version") String version,
            @RequestParam(required=false,defaultValue="1") int page,
            @RequestParam(required=false,defaultValue="15") int limit
    ){
        List<SopFileInfo> datas = new ArrayList<>();
        int count=1;
        //从第几条数据开始
        int firstIndex = (page - 1) * limit;
        //到第几条数据结束
        int lastIndex = page * limit;
        Map<String,Object> map=new HashMap<String,Object>();

        datas = sopFileInfoService.getByAreaAndTypeAndVer(area, type.toUpperCase(),version);
        count = datas.size();
        if (lastIndex > count){
            lastIndex = count;
        }
        map.put("data",datas.subList(firstIndex, lastIndex));//直接在list中截取

        map.put("code",0);
        map.put("msg","success");
        map.put("count",count);

        System.out.println(map.toString());
        return map;
    }

    @ResponseBody
    @RequestMapping("/showDepData/{area}/{type}/{version}")
    public Map<String,Object> indexShowDepData(
            @PathVariable("area") String area,
            @PathVariable("type") String type,
            @PathVariable("version") String version,
            @RequestParam(required=false,defaultValue="1") int page,
            @RequestParam(required=false,defaultValue="15") int limit
    ){
        List<DepFileInfo> depInfo = new ArrayList<>();
        int count=1;
        //从第几条数据开始
        int firstIndex = (page - 1) * limit;
        //到第几条数据结束
        int lastIndex = page * limit;
        Map<String,Object> map=new HashMap<String,Object>();
        depInfo = depFileInfoService.getInfoByAreaAndType(area,type.toUpperCase());
        count = depInfo.size();
        if (lastIndex > count){
            lastIndex = count;
        }
        map.put("data",depInfo.subList(firstIndex, lastIndex));//直接在list中截取

        map.put("code",0);
        map.put("msg","success");
        map.put("count",count);

        System.out.println(map.toString());
        return map;
    }

    @RequestMapping("/download/{fileid}/{fileType}")
    public void home(HttpServletRequest request, HttpServletResponse response,
                     @PathVariable("fileid") String fileid,
                     @PathVariable("fileType") String fileType) {

        AppFileInfo appFileInfo = null;
        SopFileInfo sopInfo = null;
        DepFileInfo depInfo = null;
        String filePath = "",fileName="";
        if(fileType.toUpperCase().equals("APP")){
            appFileInfo = appFileInfoService.getLatestInfoByMid(Integer.valueOf(fileid));
            filePath = appFileInfo.getPath();
            fileName = appFileInfo.getFileName();
        }
        if(fileType.toUpperCase().equals("SOP")){
            sopInfo = sopFileInfoService.getLatestInfoByMid(Integer.valueOf(fileid));
            filePath = sopInfo.getSopPath();
            fileName = sopInfo.getSopFileName();
        }
        if(fileType.toUpperCase().equals("DEP")){
            depInfo = depFileInfoService.getLatestInfoByMid(Integer.valueOf(fileid));
            filePath = depInfo.getDepPath();
            fileName = depInfo.getDepFileName();
        }
            //info = appSopFileInfoService.getLatestInfoBySopId(Integer.valueOf(fileid));
        //}
        //文件目录
        File downFile = new File(filePath);
        //下载
        try (InputStream inputStream = new FileInputStream(downFile);
             OutputStream outputStream = response.getOutputStream();) {

            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
